<?php
/**
 * 用户信息
 */
namespace app\api\controller;
use app\admin\model\Historyprice as HistorypriceModel;
use app\api\model\BaseConfig as BaseConfigModel;
use app\api\model\MemberTransaction as MemberTransactionModel;
use app\api\model\MemberEntrust as MemberEntrustModel;
use app\api\model\Member as MemberModel;
use app\common\model\UserMoneyLog as UserMoneyLogModel;
use think\facade\Db;
use think\facade\Queue;
use app\api\server\Worker;

class Transaction extends Baek
{
    /**
     * 买入
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function buy(MemberEntrustModel $MemberEntrust,Worker $worker)
    {

        $num  = $this->request->post('num');

        $adc_price  = $this->request->post('price');

        if(empty($num)) return api_error('','Missing parameter',$this->language);

        if(empty($adc_price)) return api_error('','Missing parameter',$this->language);

        $mid = $this->mid;

        $transaction = 0;

        //获取用户钱包
        $member = MemberModel::wallet($mid);

        //计算USDT价格
        $usdt_transaction = bcmul($num,$adc_price,4);

        //判断用户钱包是否充足
        if($member['usdt'] < $usdt_transaction) return api_error('','Sorry, your credit is running low',$this->language);

        //获取交易价格
        $adc_transaction = BaseConfigModel::config_data('adc_transaction');

        //添加委托交易
        //if($adc_price < $adc_transaction) $transaction = 1;


        Db::startTrans();
        try {


            $buy_data = Db::name('member_entrust')->where([['transaction_state','=',2],['entrust_state','=',1]])->order('money asc')->value('money');

            $buy_data = ($buy_data) ? $buy_data:$adc_transaction;

            //记录USDT数量变化
            UserMoneyLogModel::change($mid,'usdt',-$usdt_transaction,'Transaction buy','','交易减少'.$usdt_transaction.'usdt');
            //添加委托
            $MemberEntrust->add_entrust($mid,$adc_price,$num,1,1,1,$buy_data,$usdt_transaction);

          /*  if($transaction)
            {
                $MemberEntrust->add_entrust($mid,$adc_price,$num,1,1,1);
            }else
            {
                //记录ADC数量变化
                UserMoneyLogModel::change($mid,'adc',$num,'Transaction buy','','交易增加'.$num.'adc');
                //添加交易记录
                MemberTransactionModel::add_transaction($mid,1,$adc_price,$num,1,0,1);
            }*/

            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return api_error('','Purchase failed',$this->language);
        }

        return api_success();
    }

    /**
     * 卖出 数量
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function sell(MemberEntrustModel $MemberEntrust)
    {

        $num  = $this->request->post('num');

        $adc_price  = $this->request->post('price');

        if(empty($num)) return api_error('','Missing parameter',$this->language);

        if(empty($adc_price)) return api_error('','Missing parameter',$this->language);

        //获取交易价格
        $adc_transaction = BaseConfigModel::config_data('adc_transaction');

        //获取用户钱包
        $member = MemberModel::wallet($this->mid);
        //卖出数量
        if($member['adc'] < $num) return api_error('','Sorry, your credit is running low',$this->language);

        $usdt_obtain = commission($num,$adc_price);

        Db::startTrans();
        try {

            $buy_data = Db::name('member_entrust')->where([['transaction_state','=',2],['entrust_state','=',1]])->order('money asc')->value('money');

            $buy_data = ($buy_data) ? $buy_data:$adc_transaction;

            //记录ADC数量变化
            UserMoneyLogModel::change($this->mid,'adc',-$num,'Transaction sell','','交易减少'.$num.'adc');

            $MemberEntrust->add_entrust($this->mid,$adc_price,$num,1,2,1,$buy_data);

        /*    if($adc_price > $adc_transaction)
            {
                $MemberEntrust->add_entrust($this->mid,$adc_price,$num,1,2,1);
            }else
            {
                //记录USDT数量变化
                UserMoneyLogModel::change($this->mid,'usdt',$usdt_obtain,'Transaction sell','','交易增加'.$usdt_obtain.'usdt');
                //添加交易记录
                MemberTransactionModel::add_transaction($this->mid,1,$adc_price,$num,2,transaction_commission($num,$adc_price),1);
            }*/

            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return api_error('','Purchase failed',$this->language);
        }

        return api_success();
    }

    /**
     * 价格数据
     */
    public function price_data()
    {
        //实时价格
        $data['adc_transaction'] = BaseConfigModel::config_data('adc_transaction');
        //获取货币价格
        $price = MemberModel::wallet($this->mid);

        $data['usdt'] = $price['usdt'];

        $data['adc'] = $price['adc'];

        $data['range'] =   BaseConfigModel::config_data('day_increase');;

        //获取手续费
        $data['sell_money'] = BaseConfigModel::config_data('sell_money');

        return api_success($data);
    }

    /**
     * 委托列表
     */
    public function entrust_list(MemberEntrustModel $MemberEntrust)
    {
        $page  = $this->request->post('page', 1, 'intval');

        $limit  = $this->request->post('limit', 10, 'intval');

        $where[] = ['entrust_state', '=', 1];

        $where[] = ['mid', '=', $this->mid];

        $data = $MemberEntrust->entrust_list($where,$page,$limit);

        return api_success($data);
    }

    /**
     * 撤销委托
     */
    public function revoke(MemberEntrustModel $MemberEntrust)
    {
        $id  = $this->request->post('id');

        $git_data = $MemberEntrust->git_data($id,$this->mid);

        if(empty($git_data)) return api_success('','The entrustment has been concluded',$this->language);

        Db::startTrans();

        try {

            if($git_data['already_num'] > 0)$git_data['num'] = bcsub($git_data['num'],$git_data['already_num'],2);

            if($git_data['transaction_state'] == 2)
            {
                //记录ADC数量变化
                UserMoneyLogModel::change($git_data['mid'],'adc',$git_data['num'],'Transaction cancellation','','撤销委托-卖单'.$git_data['num'].'adc');
            }else
            {
                //记录USDT数量变化
                UserMoneyLogModel::change($git_data['mid'],'usdt',bcmul($git_data['num'],$git_data['money'],4),'Transaction cancellation','','撤销委托-买单'.bcmul($git_data['num'],$git_data['money'],4).'usdt');
            }

            //修改委托数据
            $MemberEntrust->up_data($git_data);

            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return api_error('','Undo failed',$this->language);
        }

        return api_success();
    }


    /**
     * 交易记录
     */
    public function transaction_record_list(MemberEntrustModel $MemberEntrust)
    {
        $page  = $this->request->post('page', 1, 'intval');

        $limit  = $this->request->post('limit', 10, 'intval');

        $where[] = ['mid', '=', $this->mid];

        $state  = $this->request->post('state');

        if($state == 1)
        {

            $data = MemberTransactionModel::transaction_record_list($where,$page,$limit);

        }else if($state == 2)
        {
            $data = $MemberEntrust->entrust_list($where,$page,$limit);
        }
        return api_success($data);

    }

}